package com.dcjt.firehotcarpad.moudle

import CarStatePool
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.Spannable
import android.text.SpannableString
import android.view.Gravity
import android.view.View
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.widget.PopupWindowCompat
import com.allen.library.SuperTextView
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.SizeUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.title.TitleBarView
import com.aries.ui.widget.progress.UIProgressView
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.base.BaseActivity
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.CarCurrentDetailEntity
import com.dcjt.firehotcarpad.fragment.BaseTabsFragment
import com.dcjt.firehotcarpad.fragment.FunctionButtonFragment
import com.dcjt.firehotcarpad.fragment.MapFragment1
import com.dcjt.firehotcarpad.manager.DataManager
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.ServiceUtils
import com.dcjt.firehotcarpad.utils.StringUtils
import com.dcjt.firehotcarpad.widget.BackgroundColorSpan
import com.juntu.loginlib.LoginCenter
import com.juntu.loginlib.contact.LoginOutContact
import com.juntu.loginlib.ex.LoginException


/**
 * Created by cj on 2021/2/20.
 * Email:codesexy@163.com
 * Function:
 * desc:主界面和处置界面的基类
 */
abstract class BaseActivity : BaseActivity(), CarStatePool.CarStateChangeObserver {


    protected lateinit var mapFragment: MapFragment1
    protected lateinit var leftFragment: BaseTabsFragment
    public lateinit var tvCarInfo: TextView

    //    public lateinit var tvCarState: RadiusTextView
    protected lateinit var bottomFragment: FunctionButtonFragment

    override fun getContentLayout(): Int = R.layout.activity_base_layout


    override fun beforeInitView() {
        super.beforeInitView()
        CarStatePool.get().registerCarStateObserver(this)
    }

    override fun setTitleBar(titleBar: TitleBarView?) {
        titleBar!!
        val actionView = View.inflate(
            this,
            R.layout.layout_main_action,
            null
        )
        tvCarInfo = actionView.findViewById<TextView>(R.id.tvCarInfo)
//        tvCarState = actionView.findViewById<RadiusTextView>(R.id.rtv_zt_car)
        tvCarInfo.text = SPUtil.get(this, SPConstant.CAR_CONFIG_NAME, "请配置车辆信息") as String

        val popView = View.inflate(this, R.layout.layout_main_pop_window, null)

        val lp = this.window.attributes

        val popupWindow = PopupWindow(this).apply {
            contentView = popView
            isOutsideTouchable = true
            isFocusable = true
            width = (SizeUtil.getScreenWidth() * 0.25).toInt()
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        }
        popView.findViewById<SuperTextView>(R.id.changeClass).setOnClickListener {
            popupWindow.dismiss()
            changeCombatTeam()
        }

        popView.findViewById<SuperTextView>(R.id.loginOut).setOnClickListener {
            popupWindow.dismiss()
            doLoginOut()
        }

        popupWindow.setOnDismissListener {
            lp.alpha = 1.0f
            window.attributes = lp
        }


        titleBar.setLeftTextDrawable(null)
            .setBgColor(Color.parseColor("#1B7DFA"))
            .addRightAction(
                titleBar.ViewAction(
                    actionView,
                    View.OnClickListener {
                        lp.alpha = 0.7f
                        window.attributes = lp
                        PopupWindowCompat.showAsDropDown(
                            popupWindow, actionView,
                            SizeUtil.dp2px(180f), SizeUtil.dp2px(7f), Gravity.BOTTOM
                        )
                    })
            )

        val rightView = titleBar.getChildAt(2)
        val rightParams = rightView.layoutParams
        rightParams.width = SizeUtil.dp2px(140f)
        rightView.layoutParams = rightParams

        //todo 设置车辆信息

        //子类设置其他相关的属性
        setTitleBarView(titleBar)

        val leftChild = titleBar.getChildAt(0)
        val params = leftChild.layoutParams
        params.width = SizeUtil.dp2px(350f)
        leftChild.layoutParams = params

    }


    /**
     *  切换作战班
     */
    private fun changeCombatTeam() {
        AlertDialogUtil.choiceCombatTeam(this, {}, {})
    }


    /**
     * 退出登录
     */
    private fun doLoginOut() {
        AlertDialogUtil.alertTips(
            this,
            resources.getString(R.string.tips),
            resources.getString(R.string.loginOutTips),
            positiveCallBack = {
                loginOut()
            })
    }

    private fun loginOut() {
        val progressView = UIProgressView(this).setMessage("退出中...")
        progressView.setCancelable(false)
        progressView.show()
        LoginCenter.getInstance().loginOut(DataManager.getInstance().user.token,
            object : LoginOutContact {
                override fun onSuccess() {
                    progressView.dismiss()
                    ServiceUtils.stopService(this@BaseActivity)
                    startActivity(Intent(this@BaseActivity, LoginActivity::class.java))
                    finish()
                }

                override fun onError(e: LoginException?) {
                    LoggerManager.e(e?.message)
                    progressView.dismiss()
                    ToastUtil.show("退出登录出错，请稍候再试")
                }
            })
    }


    override fun onDestroy() {
        super.onDestroy()
        CarStatePool.get().unRegisterCarStateObserver(this)
    }

    protected open fun setTitleBarView(titleBar: TitleBarView) {}


    override fun onCarStateChange(entity: CarCurrentDetailEntity) {

        var deptName = DataManager.getInstance().user.dept_name
        var carName = StringUtils.getNoNullString(entity.clxx!!.clmc, "")
        var carNum = StringUtils.getNoNullString(entity.clxx!!.cphm, "")
//        var carZzb = StringUtils.getNoNullString(entity.zzbxx!!.mc, "")
        var carZzb = if(StringUtils.isEmpty(entity.zzbxx!!.mc.toString())) "" else {
            ("-"+entity.zzbxx!!.mc)
        }
        var depInfo = "$deptName-$carName-$carNum$carZzb"


        var carState = entity.clxx!!.clzzztmc

        SPUtil.put(this, SPConstant.CAR_CONFIG_NAME, depInfo)

        var spannableString = SpannableString(carState + depInfo)
        spannableString.setSpan(
            BackgroundColorSpan(
                Color.parseColor("#F39E31"),
                Color.parseColor("#FFFFFF")
            ), 0, carState!!.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        tvCarInfo.text = spannableString
    }

}